package cn.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String checkCode = request.getParameter("checkCode");
        HttpSession session = request.getSession();
        String checkCode_session = (String) request.getSession().getAttribute("checkCode_session");    // 验证比较需要忽略大小写，先强制转化成字符串
        session.removeAttribute("checkCode_session");
        if (checkCode_session!=null && checkCode_session.equalsIgnoreCase(checkCode)){
            // 验证码一致
            if ("feng".equals(username) && "123".equals(password)){
                session.setAttribute("name",username);
                response.sendRedirect(request.getContextPath()+"/success.jsp");
            }else {
                // 账号密码不一致
                request.setAttribute("login_error", "用户或密码错误");
                request.getRequestDispatcher("/login.jsp").forward(request, response);
            }
        }else{
            // 验证码不一致
            request.setAttribute("login_error_checkCode","验证码错误");
            request.getRequestDispatcher("/login.jsp").forward(request,response);
        }

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);

    }
}
